package com.chenl.provider.DEMOS.本地消息表;

//import com.chenl.provider.feign.dto.common.ResultDTO;
//import com.chenl.provider.util.SnowFlakeUtil;
//import com.mysql.cj.protocol.MessageListener;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.jdbc.datasource.DataSourceTransactionManager;
//import org.springframework.transaction.TransactionDefinition;
//import org.springframework.transaction.TransactionStatus;
//
//import javax.annotation.Resource;
//
///**
// * 成本核算MQ
// */
//@Slf4j
//@RocketMqListener(topic = MqConstant.COST_TOPIC, tag = MqConstant.COST_TAG, consumerGroup = MqConstant.COST_GROUP)
//public class CostAccountingMqListener implements MessageListener<Object> {
//    @Resource
//    MqProducer mqProducer;
//    @Autowired
//    private CostAccountingService costAccountingService;
//    @Autowired
//    private LocalMessageService localMessageService;
//    @Autowired
//    private DataSourceTransactionManager dataSourceTransactionManager;
//    @Autowired
//    private TransactionDefinition transactionDefinition;
//
//
//    @Override
//    public Action consume(Object obj, Message msg) {
//        log.info("rocketConsumer-成本核算---接收到消息 MsgId:[{}] ,Topic:[{}] ,Tag:[{}] ,消息内容:[{}]", msg.getMsgID(), msg.getTopic(), msg.getTag(), JSONObject.toJSONString(obj));
//        //基于当前需求,本MQ自身不做重试,故采用手动控制事务,异常捕获 不抛出。若返回失败,会30S重试一次
//        //手动开启事务
//        TransactionStatus transactionStatus = this.dataSourceTransactionManager.getTransaction(this.transactionDefinition);
//        String msgCode = SnowFlakeUtil.next();
//        Boolean isNormal = true;
//        try {
//                                    //--------------------消费逻辑,处理成本核算开始--------------------
//            CostAccountingAdjustReqDto costAccountingAdjustReqDto = JSONObject.parseObject(JSONObject.toJSONString(obj), CostAccountingAdjustReqDto.class);
//            log.info("rocketConsumer-成本核算---请求对象:{}", JSONObject.toJSONString(costAccountingAdjustReqDto));
//            ResultDTO ok = ResultDTO.ok(costAccountingAdjustReqDto);
//                                    //--------------------消费逻辑,处理成本核算结束--------------------
//            // Mq 消息入库
//            LocalMessageReqDto localMessageReqDto=new LocalMessageReqDto();
//            localMessageReqDto.setMsgCode(msgCode);
//            localMessageReqDto.setMsgType(1);
//            localMessageReqDto.setMsgBody(JSONObject.toJSONString(ok));
//            localMessageService.save(localMessageReqDto);
//            TransactionAsyncRunnable.doAfterTransaction(() -> {
//                //事务提交,发送成功MQ todo
//                log.info("rocketConsumer-成本核算---事务提交,异步发送MQ消息,消息内容:{}", JSONObject.toJSONString(ok));
//                boolean flag = mqProducer.sendTopicMqProducer(MqConstant.COST_ACOUNTING_RETURN_TOPIC, MqConstant.COST_ACOUNTING_RETURN_TAG, JSONObject.toJSONString(ok));
//                if (flag){
//                    localMessageService.deleteByMsgCodes(msgCode);
//                }
//            }, null);
//        } catch (Exception e) {
//            log.error("rocketConsumer-成本核算---MsgId:{},应用MQ消费异常,Topic:[{}] ,Tag:[{}] ，Body:[{}] ,异常信息:[{}]", msg.getMsgID(), msg.getTopic(), msg.getTag(), msg, e.toString());
//            isNormal=false;
//            //回滚事务
//            this.dataSourceTransactionManager.rollback(transactionStatus);
//            //失败后续处理
//            catchMethod(e,msgCode);
//            return Action.CommitMessage;
//        }
//        //提交事务
//        if (isNormal){
//            this.dataSourceTransactionManager.commit(transactionStatus);
//        }
//        return Action.CommitMessage;
//    }
//
//    private void catchMethod(Exception e,String msgCode) {
//        //重新开启一个事务 失败消息入库(不论提交还是回滚,都直接发MQ)
//        TransactionStatus transactionStatus2 = this.dataSourceTransactionManager.getTransaction(transactionDefinition);
//        ResultDTO errorRes = ResultDTO.error(e.toString());
//        LocalMessageReqDto localMessageReqDto=new LocalMessageReqDto();
//        localMessageReqDto.setMsgType(1);
//        localMessageReqDto.setMsgCode(msgCode);
//        localMessageReqDto.setMsgBody(JSONObject.toJSONString(errorRes));
//        localMessageService.save(localMessageReqDto);
//        TransactionAsyncRunnable.doAfterTransaction(()->{
//            log.info("rocketConsumer-成本核算---事务回滚,异步发送MQ消息,消息内容:{}", JSONObject.toJSONString(errorRes));
//            mqProducer.sendTopicMqProducer(MqConstant.COST_ACOUNTING_RETURN_TOPIC, MqConstant.COST_ACOUNTING_RETURN_TAG, JSONObject.toJSONString(errorRes));
//            //删除本地消息表数据
//            localMessageService.deleteByMsgCodes(msgCode);
//        },()->{
//            log.info("rocketConsumer-成本核算---事务回滚,发送MQ消息,消息内容:{}", JSONObject.toJSONString(null));
//            mqProducer.sendTopicMqProducer(MqConstant.COST_ACOUNTING_RETURN_TOPIC, MqConstant.COST_ACOUNTING_RETURN_TAG, JSONObject.toJSONString(errorRes));
//        });
//        this.dataSourceTransactionManager.commit(transactionStatus2);
//    }
//
//
//    NewCostAccountingResDto copyCostAccountingResDto(CostAccountingResDto r) {
//        NewCostAccountingResDto newCostAccountingResDto = new NewCostAccountingResDto();
//        newCostAccountingResDto.setCostAccountingStatus(r.getCostAccountingStatus());
//        newCostAccountingResDto.setId(r.getId());
//        newCostAccountingResDto.setAfterTaxStockAmount(r.getAfterTaxStockAmount());
//        newCostAccountingResDto.setCreateTime(r.getCreateTime());
//        newCostAccountingResDto.setCreateUserId(r.getCreateUserId());
//        newCostAccountingResDto.setCreateUserName(r.getCreateUserName());
//        newCostAccountingResDto.setEndTime(r.getEndTime());
//        newCostAccountingResDto.setEndingStock(r.getEndingStock());
//        newCostAccountingResDto.setSkuCode(r.getSkuCode());
//        newCostAccountingResDto.setSkuName(r.getSkuName());
//        newCostAccountingResDto.setStartTime(r.getStartTime());
//        newCostAccountingResDto.setNoTaxStockAmount(r.getNoTaxStockAmount().setScale(11, BigDecimal.ROUND_HALF_UP).toPlainString());
//        newCostAccountingResDto.setTaxStockAmount(r.getTaxStockAmount().setScale(11, BigDecimal.ROUND_HALF_UP).toPlainString());
//        newCostAccountingResDto.setTaxUnitPrice(r.getTaxUnitPrice());
//        newCostAccountingResDto.setNoTaxUnitPrice(r.getNoTaxUnitPrice());
//        newCostAccountingResDto.setMonthKnotStatus(r.getMonthKnotStatus());
//        return newCostAccountingResDto;
//    }
//}
